package com.pricl.biz.admin.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pricl.biz.admin.service.AdminUserService;
import com.pricl.biz.admin.service.IndexService;
import com.pricl.frame.core.R;

/**
 * <p>
 * 框架控制器
 * </p>
 * 
 */
@Controller("admin.index.controller")
@RequestMapping("/admin")
public class IndexController {
	
	@Autowired
	IndexService service;

	@Autowired
	AdminUserService adminUserService;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		return "/admin/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public @ResponseBody R login(String username, String password, String code, HttpServletRequest request,
			HttpServletResponse response) {
		Subject currentUser = SecurityUtils.getSubject();
		// System.out.println(username+"::"+password);
		if (!currentUser.isAuthenticated()) {
			
			return login(currentUser, username, password);
		} else {
			// 重复登录
			// TODO 日志处理
			currentUser.logout();
			return login(currentUser, username, password);
		}
	}

	private R login(Subject currentUser, String username, String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		// RemeberMe
		token.setRememberMe(false);
		try {
			currentUser.login(token);
			SecurityUtils.getSubject().getSession().setTimeout(3600000);
		} catch (UnknownAccountException uae) {
			return R.error("UnknownAccountException failure");
		} catch (IncorrectCredentialsException ice) {
			return R.error("IncorrectCredentialsException failure");
		} catch (LockedAccountException lae) {
			return R.error("LockedAccountException failure");
		} catch (AuthenticationException ae) {
			return R.error("AuthenticationException failure");
		}
		return R.ok("success");
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index() {
		return "/admin/index";
	}

	@RequestMapping(value = "desktop", method = RequestMethod.GET)
	public String desktop() {
		return "/admin/desktop";
	}

}
